<?php

namespace Upfor\UpforPHP\Http;

class Url {

    public static function buildUrl($url, array $params = array()) {
        $url = '/' . trim($url, '/');

        ksort($params);
        foreach ($params as $key => $value) {
            $url .= '/' . $key . '/' . $value;
        }

        return $url;
    }

    /**
     * Parse URL
     *
     * @param  string  $url
     * @param  boolean $setRequest
     * @return array
     */
    public static function parseUrl($url, $setRequest = false) {
        list($path, $var) = self::parseUrlPath($url);

        $controller = array_shift($path);
        if (empty($controller)) {
            $controller = isset(config('route')['defaultController']) ? ucfirst(config('route')['defaultController']) : 'Index';
        }

        $action = array_shift($path);
        if (empty($action)) {
            $action = isset(config('route')['defaultAction']) ? config('route')['defaultAction'] : 'index';
        }

        $params = self::parseUrlParams(implode('/', $path));

        // set up the request data
        if ($setRequest) {
            request()->setController($controller);
            request()->setAction($action);
            request()->setUrlParams($params);
        }

        // Return to parse the data
        return array(
            'controller' => $controller,
            'action' => $action,
            'params' => $params,
        );
    }

    private static function parseUrlParams($url) {
        $params = [];
        preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$params) {
            $params[$match[1]] = strip_tags($match[2]);
        }, $url);

        return $params;
    }

    private static function parseUrlPath($url) {
        $url = trim($url, '/');
        $path = $var = [];
        if (false !== strpos($url, '?')) {
            // [控制器/操作?]参数1=值1&参数2=值2...
            $info = parse_url($url);
            $path = explode('/', $info['path']);
            parse_str($info['query'], $var);
        } elseif (strpos($url, '/')) {
            // [控制器/操作]
            $path = explode('/', $url);
        } elseif (false !== strpos($url, '=')) {
            // 参数1=值1&参数2=值2...
            parse_str($url, $var);
        } else {
            $path = [$url];
        }

        return [$path, $var];
    }

}
